﻿using System;
using System.Web.Mvc;
using Yeap.Config;
using Yeap.Kernel.Security;

namespace Yeap.Controllers.Filters
{
    public class AuthenticationFilter : AuthorizeAttribute
    {
        private bool _isRequired = true;

        public AuthenticationFilter()
        {

        }

        public AuthenticationFilter(bool isRequired)
        {
            _isRequired = isRequired;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var controller = (Yeap.Controllers.Controller)filterContext.Controller;

            if (!_isRequired)
            {
                return;
            }

            if (controller.Name == "Default")
            {
                string url = controller.Url.Action(Constants.Actions.LoginAction, Constants.Controllers.Account, new
                {
                    ReturnUrl = controller.Request.Url.AbsoluteUri.ToLower().Contains("/back.aspx") ? String.Empty :
                        controller.Request.Url.AbsoluteUri
                });
                filterContext.Result = new RedirectResult(url);
            }

            if (!LoginUtils.CurrentUserAccount.IsLogged)
            {
                string url = controller.Url.Action(Constants.Actions.LoginAction, Constants.Controllers.Account, new
                {
                    ReturnUrl = controller.Request.Url.AbsoluteUri.ToLower().Contains("/back.aspx") ? String.Empty :
                        controller.Request.Url.AbsoluteUri
                });
                filterContext.Result = new RedirectResult(url);
            }
        }
    }

}